<?php
namespace App\Controller\Admin;

use App\Query\UserQuery;
use App\Query\UserLogQuery;
use App\Query\UserTransferQuery;
use App\Query\OrderQuery;
use App\Repository\UserRepository;

class UserController extends Controller
{
    // 列表
    public function index()
    {
        return UserQuery::query(
            UserQuery::model(),
            $this->inputs('username', 'user_id', 'level_id', 'phone')
        )->paginate(15)->toArray();
    }
    
    // 更新
    public function update($id)
    {
        $data = $this->inputs('phone', 'level_id', 'money_status', 'lock_status');
        
        if($user = UserRepository::find($id))
        {
            if($user->update($data))
            {
                $this->message('ok');
            }
        }
        
        $this->error('error');
    }
    
    // 日志
    public function log()
    {
        return UserLogQuery::query(
            UserLogQuery::model(),
            $this->inputs('user_id', 'type', 'money_type', 'content', 'time')
        )->paginate(15)->toArray();
    }

    // 转帐
    public function transfer()
    {
        return UserTransferQuery::query(
            UserTransferQuery::model(),
            $this->inputs('user_id', 'to_user_id', 'money_type', 'time')
        )->paginate(15)->toArray();
    }
    
    // 系统派送
    public function money($id)
    {
        if($user = UserRepository::find($id))
        {
            if($user->addMoney($this->input('type'), $this->input('money'), $this->input('content')))
            {
                $this->message('ok');
            }
        }
        
        $this->error('error');
    }
    
    // 个人业绩
    public function moneyAll($id)
    {
        if($user = UserRepository::find($id))
        {
            if($user->addMoneyAll($this->input('money')))
            {
                $this->message('ok');
            }
        }
        
        $this->error('error');
    }
    
    // 修改静态释放时间，防止系统锁定帐号
    public function moneyRemainTime($id)
    {
        if($user = UserRepository::find($id))
        {
            if($user->setMoneyRemainTime($this->input('time')))
            {
                $this->message('ok');
            }
        }
        
        $this->error('error');
    }
    
    // 统计未释放订单
    public function orderRemain($id)
    {
        $money = 0;
        
        if($user = UserRepository::find($id))
        {
            $money = OrderQuery::remain(OrderQuery::user($user))->sum('money_remain');
        }
        
        return ['money' => (float) $money];
    }
}